package com.resource.base.config;

import com.resource.project.entity.system.Menu;
import com.resource.project.entity.system.Role;
import com.resource.project.service.system.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * 根据用户传来的请求地址分析出请求需要的角色
 */
@Component
public class MyFilterInvocationSecurityMeta implements FilterInvocationSecurityMetadataSource {
    @Autowired
    private IMenuService menuService;
    AntPathMatcher matcher = new AntPathMatcher();
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        //当签的请求地址
        String request = ((FilterInvocation) o).getRequestUrl();
        List<Menu> menus = menuService.getAllMenuWithRole();
        for(Menu menu : menus){
            if (matcher.match(menu.getUrl(),request)){
                //匹配上
                List<Role> roles = menu.getRoles();
                return SecurityConfig.createList(roles.stream().map(t->t.getName()).toArray(String[]::new));
            }
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
